import { createRouter, createWebHistory } from 'vue-router';
import Dashboard from '../views/Dashboard.vue';
import UserManagement from '../views/UserManagement.vue';
import IngredientManagement from '../views/IngredientManagement.vue';
import FoodDetail from '../views/FoodDetail.vue';
import RecipeManagement from '../views/RecipeManagement.vue';
import OrderManagement from '../views/OrderManagement.vue';
import NutritionAnalysis from '../views/NutritionAnalysis.vue';
import NotFound from '../views/NotFound.vue';
import Login from '../views/Login.vue';

const routes = [
  { path: '/login', component: Login },
  { path: '/', component: Dashboard },
  { path: '/user-management', component: UserManagement },
  { path: '/ingredient-management', component: IngredientManagement },
  {
    path: '/food/detail/:id', // 带ID参数的详情页路由
    name: 'FoodDetail',
    component: FoodDetail,
    props: true // 通过props传递路由参数
  },
  { path: '/recipe-management', component: RecipeManagement },
  { path: '/order-management', component: OrderManagement },
  { path: '/nutrition-analysis', component: NutritionAnalysis },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn');
  if (to.path === '/login') {
    next();
  } else {
    if (isLoggedIn) {
      next();
    } else {
      next('/login');
    }
  }
});

export default router;